from django import forms

from oracle.models import ORole


class RoleForm(forms.ModelForm):
    title = forms.CharField(
        required=True,
        widget=forms.widgets.TextInput(attrs={'class': "form-control", 'placeholder': 'NAME'}),
        max_length=30,
        strip=True,
        label="角色名字",
        error_messages={
            "required": "角色名字不能为空",
            "unique": "角色名字已存在",
        }
    )

    class Meta:
        model = ORole
        fields = ("key", "title", "status", "level")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 添加默认前端class属性
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'


class RoleCreateForm(RoleForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        required_false_keys = ["key", "status", "level"]
        for key in required_false_keys:
            if key in self.fields:
                self.fields[key].required = False


class RoleUpdateForm(RoleForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        required_keys = ["key", "status", "level"]
        for key in required_keys:
            if key in self.fields:
                self.fields[key].required = True
                self.fields[key].error_messages = {
                    "required": f"{self.fields[key].label}字段不能为空",
                }
